#!groovy

def serverDir,projectName,version,image
pipeline {
    agent any
    environment {
        gitRepositoryUrl = "http://git.cfhy.work/web/cf-systemAdmin.git"
        credentialsId = "0f305fa1-acba-4c0a-9bdf-cdd66f4ea128"
        replicas = 1
        imagePullPolicy = "IfNotPresent" //IfNotPresent
        k8sOpsDir = "/data/jenkins/cfhy-k8s/k8s-test01/web"
        PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"

    }
    parameters {
        //gitParameter (name: 'branchAndTag', type: 'PT_BRANCH_TAG', defaultValue: 'master', description: '请选择需要构建的分支或版本')
        choice(name: 'dockerRegistry', choices: ['swr.cn-north-4.myhuaweicloud.com'], description: '请选择docker镜像仓库地址，vpc环境速度较快，但需要环境支撑')
        choice(name: 'dockerRegistryNamespace', choices: ['cfhy-dev'], description: '请选择docker镜像命名空间')
        choice(name: 'k8sNamespace', choices: ['test01'], description: '请选择k8s命名空间')
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }
    tools {
        nodejs 'nodejs'
    }

    stages {
        stage('pull code') {
            steps {
                sh "rm -rf ./* .git*"
                script{
                    def changeLogSets = checkout([$class: 'GitSCM',
                                                  branches: [[name: "$GIT_BRANCHES"]],
                                                  doGenerateSubmoduleConfigurations: false,
                                                  extensions: [],
                                                  submoduleCfg: [],
                                                  userRemoteConfigs: [[credentialsId: "${credentialsId}", url: "${gitRepositoryUrl}"]]])
                    version = changeLogSets['GIT_COMMIT']
                }

            }
        }
        stage('npm build') {
            steps {
                sh """
                  npm install --unsafe-perm=true --allow-root
                  npm run build
                  """
            }
        }
        stage('build image') {
            steps {
                script{
                    def branchTag = "origin/dev"
                    if(branchTag.contains("origin/") || branchTag == null || "" == branchTag || "master" == branchTag || "dev" == branchTag){
                        version = "${BUILD_ID}-" + version.substring(0, 7)
                    } else {
                        version = "${BUILD_ID}-" + branchTag
                    }
                    //def parentProjectName = "${JOB_NAME}".split("/")["${JOB_NAME}".split("/").length - 1]
                    def parentProjectName = "${JOB_NAME}".split("test-")["${JOB_NAME}".split("test-").length - 1]
                    if(parentProjectName.equals("front-admin")){
                        projectName = "${parentProjectName}"
                        serverDir = "${WORKSPACE}"
                    }else {
                        projectName = "front-admin"
                        serverDir = "${WORKSPACE}"
                    }
                    println "[INFO] ====> projectName:$projectName"
                    println "[INFO] ====> version:$version"
                    println "[INFO] ====> serverDir:$serverDir"
                    image = """${params.dockerRegistry}/${params.dockerRegistryNamespace}/$projectName:$version"""
                    println "[INFO] ====> image:$image"

                    sh """
                        set +x
                        echo "${serverDir}"
                        cd ${serverDir}
                        cp -r ${k8sOpsDir}/front-admin/Dockerfile  ${k8sOpsDir}/front-admin/nginx ./
                        docker build -t $image .
                        set -x
                    """
                }
            }
        }
        stage('push image') {
            steps {
                sh "docker push $image && docker rmi $image"
            }
        }
        stage('deploy to k8s') {
            steps {
                script{
                    def k8sEnv
                    if("${params.k8sNamespace}.equals('test')"){
                        k8sEnv = "test"
                    } else {
                        k8sEnv = "dev"
                    }
                    def projectYamlDir = "${env.k8sOpsDir}/yaml/$k8sEnv/$projectName"
                    println "[INFO] ====> projectYamlDir:$projectYamlDir"

                    sh """
                        set +x
                        mkdir -p ${projectYamlDir}
                        cd ${projectYamlDir}               
                        cp -f "${k8sOpsDir}/template/front-admin.yaml" "${projectYamlDir}/${projectName}.yaml"
                        sed -i "s,{{projectName}},${projectName},g" ${projectName}.yaml
                        sed -i "s,{{namespace}},${k8sNamespace},g" ${projectName}.yaml
                        sed -i "s,{{replicas}},${replicas},g" ${projectName}.yaml
                        sed -i "s,{{image}},${image},g" ${projectName}.yaml
                        sed -i "s,{{imagePullPolicy}},${imagePullPolicy},g" ${projectName}.yaml
                        cat ${projectName}.yaml
                        echo "[INFO] yaml file completed!"
                        kubectl apply -f ${projectName}.yaml --validate=false
                        set -x
                    """
                }
            }
        }
        stage('health check') {
            steps {
                echo " TO DO !"
            }
        }
    }
}
